// pkg/stats/api.go
package stats

import (
	"encoding/json"
	"net/http"
)

// StatsHandler HTTP 统计处理器
type StatsHandler struct {
	collector *Collector
}

// NewStatsHandler 创建统计处理器
func NewStatsHandler(collector *Collector) *StatsHandler {
	return &StatsHandler{collector: collector}
}

// ServeHTTP 处理 HTTP 请求
func (h *StatsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/stats/metrics" {
		h.handleMetrics(w, r)
	} else if r.URL.Path == "/stats/history" {
		h.handleHistory(w, r)
	} else {
		http.NotFound(w, r)
	}
}

// handleMetrics 处理当前指标请求
func (h *StatsHandler) handleMetrics(w http.ResponseWriter, r *http.Request) {
	metrics := h.collector.GetMetrics()
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(metrics)
}

// handleHistory 处理历史数据请求
func (h *StatsHandler) handleHistory(w http.ResponseWriter, r *http.Request) {
	limit := 100
	if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
		fmt.Sscanf(limitStr, "%d", &limit)
	}

	history := h.collector.GetHistory(limit)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(history)
}
